// components/picker/index.ts
import getDateInfo from './date'
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    startDate: {
      type: String,
      default: ''
    },
    endDate: {
      type: String,
      default: ''
    },
    date: {
      type: String,
      default: ''
    }
  },

  data: {
    years: [],
    year: 0,
    months: [],
    month: 0,
    days: [],
    day: 0,
    value: [0, 0, 0],  //每列都滚动到第一个
    dateValue: ''
  },
  //组件生命周期函数 - 在组件实例进入页面节点树时执行
  attached: function () {
    console.log(this.properties.date)
    let startDate: any = null
    // 判断当前时间是什么
    if (this.properties.date != '') {
      startDate = new Date(this.properties.date)
    } else {
      startDate = new Date(this.properties.startDate)
    }
    let year = startDate.getFullYear()
    let month = startDate.getMonth() + 1
    let day = startDate.getDate()
    console.log(this.properties.endDate)
    let { years, months, days } = getDateInfo(year, month, this.properties.startDate, this.properties.endDate)
    console.log(years)
    this.setData({
      year, month, day, years, months, days
    })
    // 滚动到指定的位置
    let yearIndex = years.indexOf(year)
    let monthIndex = months.indexOf(month)
    let dayIndex = days.indexOf(day)
    this.setData({
      value: [yearIndex, monthIndex, dayIndex]
    })
  },

  /**
   * 组件的方法列表
   */
  methods: {
    bindChange(e: any) {
      // console.log("执行了bindChange")
      let that: any = this
      // 获取滑动的位置
      const val = e.detail.value
      let y = that.data.years[val[0]]
      let m = that.data.months[val[1]]
      let { years, months, days } = getDateInfo(y, m, that.properties.startDate, that.properties.endDate)

      // 判断是否只有年份动了
      if (that.data.value[0] != val[0]) {
        // 记录之前的月份和天数
        let fm = that.data.month
        let fd = that.data.day
        let mIndex = months.indexOf(fm)  //获取下标
        let dIndex = days.indexOf(fd)  //获取下标
        if (mIndex != -1) {
          // 如果新的年份有之前的月份
          val[1] = mIndex
        }
        if (dIndex != -1) {
          // 如果新的年份有之前的日期
          val[2] = dIndex
        }
      } else if (that.data.value[1] != val[1]) {
        // 只有月份动了
        // 记录之前的天数
        let fd = that.data.day
        let dIndex = days.indexOf(fd)  //获取下标
        if (dIndex != -1) {
          // 如果新的年份有之前的日期
          val[2] = dIndex
        }
      }

      let year = years[val[0]]
      let month = months[val[1]]
      let day = days[val[2]]
      let dateValue = year + '-' + month + '-' + day
      that.setData({
        // value: val,
        year, month, day, years, months, days,
        dateValue
      })
      // 向页面传值
      that.triggerEvent('change', {
        dateValue
      })
      that.setData({
        value: val
      })
    },
  },
})
